package co2.bean;

import java.io.Serializable;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.hibernate.id.UUIDHexGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataIntegrityViolationException;

import co2.engine.BeanGetter;
import co2.engine.Co2Constants;
import co2.engine.DAOInterface;
import co2.pojos.MstUser;

@ManagedBean
@ViewScoped
public class SignUpBean extends AbstractBean implements Serializable {
	private static final long serialVersionUID = 1L;

	private MstUser user;
	private String pass1;
	private String pass2;
	
	@Autowired
	@Qualifier("daoI")
	private DAOInterface dao;
	
	@PostConstruct
	public void postCon(){
		user = new MstUser();
	}

	public void submit(){
		if(pass1.equals(pass2)){
			String uuid = (String) (new UUIDHexGenerator()).generate(null, null);
			user.setUuid(uuid);
			user.setPassword(pass1);
			user.setRole("K1");
			user.setStatus("ACTIVE"); //sementara dihardcode dlu tidak butuh email confirmation
			String userId = user.getUserId();
//			String email = user.getEmail();
			try{
				dao.save(user);
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Success",""));
				
			}catch(DataIntegrityViolationException cve){
				cve.printStackTrace();
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"User Id: "+user.getUserId()+" sudah terpakai",""));
			}catch(Exception e){
				e.printStackTrace();
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error saving data",""));
			}
			
			try{

				String path = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
				
//				String realPath="localhost:15001/co2";

				/*StringBuffer sb = new StringBuffer();
				sb.append(Co2Constants.REAL_PATH).append("/jsf/target/konfirmasi.jsf?faces-redirect=true&userId=").append(userId).append("&uuid=").append(uuid);*/
//				sendEmail(sb.toString(), user);
				FacesContext.getCurrentInstance().getExternalContext().redirect(path+"/jsf/target/success_sign_up.jsf");
			}catch(Exception e2){
				e2.printStackTrace();
//				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error sending email",""));
			}finally{
				user = new MstUser();
			}
		}else{
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Password not match",""));
		}
	}
	
	public void sendEmail(String link, MstUser user){

		final String username = "wikamailrobot";
		final String password = "insertpasswordhere";

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("wikamailrobot@gmail.com"));
			message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getEmail()));
			message.setSubject("Signup Confirmation");
			message.setText(prepareString(link, user));

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			
			e.printStackTrace();
//			throw new RuntimeException(e);
		}
	
	}
	
	public String prepareString(String link, MstUser user){
		StringBuffer sb = new StringBuffer();
		sb.append("Dear ").append(user.getUsername()).append(",\n\n\n")
			.append("Terimakasih telah melakukan pendaftaran pada system kami, Copy link dibawah ini ke browser untuk konfirmasi: ")
			.append("\n\n\n\n").append(link).append("\n\n\n\n\n\n\n").append("Best Regards,").append("\nAdmin");
		return sb.toString();
	}
	public MstUser getUser() {
		return user;
	}

	public void setUser(MstUser user) {
		this.user = user;
	}

	public String getPass1() {
		return pass1;
	}

	public void setPass1(String pass1) {
		this.pass1 = pass1;
	}

	public String getPass2() {
		return pass2;
	}

	public void setPass2(String pass2) {
		this.pass2 = pass2;
	}

	public DAOInterface getDao() {
		return dao;
	}

	public void setDao(DAOInterface dao) {
		this.dao = dao;
	}
}
